package com.dindang.maintenance.mvp.ui.widget;

import android.app.Activity;
import android.app.Dialog;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.dindang.maintenance.R;
import com.dindang.maintenance.mvp.ui.adapter.custom.MyImagePagerAdapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by cxw on & 2018/11/2
 */
public class ScaleImageView {
    private static final byte URLS = 0;//网络查看状态
    private static final byte FILES = 1;//本地查看状态
    private byte status;//用来表示当前大图查看器的状态

    private Activity activity;

    private List<String> urls;//网络查看状态中传入的要查看的图片的Url的List
    private List<File> files;//本地查看状态中传入的要查看的图片对应的file对象的List
    private List<File> downloadFiles;//网络查看状态中从Url下载下来的图片对应的Url的List

    private int selectedPosition;//表示当前被选中的ViewPager的item的位置

    private Dialog dialog;//用于承载整个大图查看器的Dialog

    private ImageView download;//保存图片到本地的按钮
    private TextView imageCount;//用于显示当前正在查看第几张图片的TextView
    private ViewPager viewPager;

    private List<View> views;//ViewPager适配器的数据源
    private MyImagePagerAdapter adapter;

    private OnDeleteItemListener listener;
    private int startPosition;//打开大图查看器时，想要查看的ViewPager的item的位置

    public interface OnDeleteItemListener {
        void onDelete(int position);
    }

    public ScaleImageView(Activity activity) {
        this.activity = activity;
        init();
    }

    public void setUrls(List<String> imagePaths, int startPosition) {
        if (this.urls == null) {
            this.urls = new ArrayList<>();
        } else {
            this.urls.clear();
        }
        for (String imagePath : imagePaths)
            this.urls.add(imagePath);
        status = URLS;
        if (downloadFiles == null) {
            downloadFiles = new ArrayList<>();
        } else {
            downloadFiles.clear();
        }
        this.startPosition = startPosition++;
        String text = startPosition + "/" + urls.size();
        imageCount.setText(text);
    }

    public void setFiles(List<File> files, int startPosition) {
        if (this.files == null) {
            this.files = new LinkedList<>();
        } else {
            this.files.clear();
        }
        this.files.addAll(files);
        status = FILES;
        download.setVisibility(View.GONE);
        this.startPosition = startPosition++;
        String text = startPosition + "/" + files.size();
        imageCount.setText(text);
    }

    public void setOnDeleteItemListener(OnDeleteItemListener listener) {
        this.listener = listener;
    }

    private void init() {
        RelativeLayout relativeLayout = (RelativeLayout) activity.getLayoutInflater().inflate(R.layout.maintenance_dialog_scale_image, null);
        download = (ImageView) relativeLayout.findViewById(R.id.maintenance_scale_image_save);
        imageCount = (TextView) relativeLayout.findViewById(R.id.maintenance_scale_image_count);
        viewPager = (ViewPager) relativeLayout.findViewById(R.id.maintenance_scale_image_view_pager);
        dialog = new Dialog(activity, R.style.Dialog_Fullscreen);
        dialog.setContentView(relativeLayout);
        download.setOnClickListener(v -> {
            try {
                MediaStore.Images.Media.insertImage(activity.getContentResolver(),
                        downloadFiles.get(selectedPosition).getAbsolutePath(),
                        downloadFiles.get(selectedPosition).getName(), null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Snackbar.make(viewPager, "图片保存成功", Snackbar.LENGTH_SHORT).show();
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectedPosition = position;
                String text = ++position + "/" + views.size();
                imageCount.setText(text);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void create() {
        dialog.show();
        views = new ArrayList<>();
        adapter = new MyImagePagerAdapter(views, dialog);
        if (status == URLS) {
            for (String url : urls) {
                FrameLayout frameLayout = (FrameLayout) activity.getLayoutInflater().inflate(R.layout.maintenance_view_scale_image, null);
                SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) frameLayout.findViewById(R.id.maintenance_scale_image_view);
                imageView.setOnClickListener(view -> dialog.dismiss());
                views.add(frameLayout);
                IOThread.getSingleThread().execute(() -> {
                    File downLoadFile;
                    try {
                        downLoadFile = Glide.with(activity).load(url).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
                        downloadFiles.add(downLoadFile);
                        activity.runOnUiThread(() -> imageView.setImage(ImageSource.uri(Uri.fromFile(downLoadFile))));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            viewPager.setAdapter(adapter);
        } else if (status == FILES) {
            for (File file : files) {
                FrameLayout frameLayout = (FrameLayout) activity.getLayoutInflater().inflate(R.layout.maintenance_view_scale_image, null);
                SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) frameLayout.findViewById(R.id.maintenance_scale_image_view);
                views.add(frameLayout);
                imageView.setImage(ImageSource.uri(Uri.fromFile(file)));
            }
            viewPager.setAdapter(adapter);
        }
        viewPager.setCurrentItem(startPosition);
    }
}
